import React from 'react';
import { Row, Button, Spin } from 'antd';
import { inject, observer } from 'mobx-react';
import classNames from 'classnames';
import { WeaLocaleProvider, WeaInput, WeaInputLocale, WeaHelpfulTip, WeaTab } from 'ecCom';
import pageApi from '../../../../apis/page';

const getLabel = WeaLocaleProvider.getLabel;
const getMultiStrFromBase64 = WeaInputLocale.getMultiStrFromBase64;

const FORMSUBMIT = 'formSubmit';
const MESSAGEALERT = 'messageAlert';
const topTab = [
    { title: getLabel(520805, '表单填写相关'), viewcondition: '0' },
    { title: getLabel(520806, '消息提醒相关'), viewcondition: '1' }];

const getTips = (type) => {
    let currentTips = '';

    switch (type) {
        case 'APPLICATION_FORM_TIP':
            currentTips = `${getLabel('527285','参数变量说明')}：
                <br/>1.{appname} ${getLabel('381923','应用名称') }
                <br/>2.{creater} ${getLabel('527286','应用创建者') }
                <br/>3.{applicant} ${getLabel('527287','表单填写权限申请人')}
                <br/>4.{applicantdept} ${getLabel('17895','申请人部门') }
                <br/>5.{applicantdate} ${getLabel('855','申请日期') }
                <br/>6.{applicanttime} ${getLabel('390653','申请时间')}`;
            break;
        case 'AGREE_SUBMIT_TIP':
            currentTips = `${getLabel('527285','参数变量说明')}：
            <br/>1.{appname} ${getLabel('381923','应用名称') }
            <br/>2.{handler} ${getLabel('527288','权限申请处理人') }`;
            break;
        case 'REFUSE_SUBMIT_TIP':
            currentTips = `${getLabel('527285','参数变量说明')}：
            <br/>1.{appname} ${getLabel('381923','应用名称') }
            <br/>2.{handler} ${getLabel('527288','权限申请处理人') }`;
            break;
        case 'MESSAGE_ARRIVAL_TIP':
            currentTips = `${getLabel('527285','参数变量说明')}：
            <br/>1.{appname} ${getLabel('381923','应用名称') }
            <br/>2.{creater} ${getLabel('527286','应用创建者') }
            <br/>3.${getLabel('527289','{字段名称} 引用表单字段的内容,如{field001}')}`;
            break;
        default:
            break;
    }

    return currentTips;
};

const ClerkItem = ({ property, propertyType, title, message, onClerkChange }) => {
    const errorMsgCls = classNames({
        'clerk-error': !message,
    });

    return (
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@vn14xu`}>
            <label>{title}</label>
            <div className={errorMsgCls}>
                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@dvxm4d`} isBase64={true} inputType={'multilang'} value={getMultiStrFromBase64(message)} onChange={e => onClerkChange(e, property)} data-property={property} />
                {propertyType !== MESSAGEALERT ? null :
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@3uhncx`}
                      width={196}
                      title={getTips(property)}
                    />
                }
                {!message && <div className="error-msg">{`${title}${getLabel('513479', '不能为空!')}`}</div>}
            </div>
        </Row>
    );
};

@inject('edcFormDesignerStore')
@observer
export default class Clerk extends React.Component {
    constructor(props) {
        super();
        this.state = {
            isSaving: false,
            clerks: [],
            saveFlag: true,
            selectedKey: '0',
        };
        this.store = props.edcFormDesignerStore;
    }

    componentDidMount() {
        const { appid } = this.store;

        pageApi.getClerkInfo({ appid })
        .then(response => this.setState({ clerks: response }));
    }

    onClerkChange = (value, property) => {
        const { clerks } = this.state;
        const newClerks = clerks.map((item) => {
            if (item.property === property) {
                item.message = value;
            }
            return item;
        });

        this.setState({ clerks: newClerks, saveFlag: Boolean(value) });
    }

    onSave = () => {
        const { appid } = this.store;
        const { clerks, saveFlag } = this.state;

        if (!saveFlag) return;

        const newClierks = clerks.map((item) => {
            const message = item.message;
            if (message.indexOf('base64_')) {
                item.message = getMultiStrFromBase64(message);
            }
            return item;
        });

        pageApi.saveClerk({ appid, wordings: JSON.stringify(newClierks) });
    }

    getCkerkEles = (data, type) => {
        const newData = data.filter(item => item.propertyType == type);

        const ckerkEles = newData.map((item, index) => (<ClerkItem ecId={`${this && this.props && this.props.ecId || ''}_ClerkItem@r2rmn7@${index}`}
          property={item.property}
          propertyType={item.propertyType}
          title={item.title}
          message={item.message}
          onClerkChange={this.onClerkChange}
        />
        ));

        return ckerkEles;
    }

    render() {
        const { isSaving, clerks, selectedKey } = this.state;
        const clerkType = selectedKey == '0' ? FORMSUBMIT : MESSAGEALERT;

        if (clerks.length <= 0) return (<div className="loading"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@6w188w`} /></div>);

        return (
            <div className="es-clerk">
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@3vbyt3`}
                  datas={topTab}
                  keyParam="viewcondition"
                  selectedKey={selectedKey}
                  onChange={selectedKey => this.setState({ selectedKey })}
                />
                {this.getCkerkEles(clerks, clerkType)}
                <div className="clerk-btn">
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xim24y`} type="primary"
                  icon={isSaving && 'loading'}
                  onClick={this.onSave}
                >
                   {getLabel('86', '保存')}
                </Button>
                </div>
            </div>
        );
    }
}
